<?php
date_default_timezone_set('PRC');

/**
 * 请求HTML页面
 */
function http($url, $post_data = [], $headers = [])
{
	//初始化
	$ch = curl_init();
	
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 15);
	// curl_setopt($ch, CURLOPT_HEADER, 0);

	// $proxy = '127.0.0.1';
	// curl_setopt($ch, CURLOPT_PROXY, $proxy);
	// $proxyport = '8888';
	// curl_setopt($ch, CURLOPT_PROXYPORT, $proxyport);

	// post数据
	if (count($post_data)) {
		$post_str = http_build_query($post_data);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
	}

	// 头信息
	if (count($headers)) {
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	}

	// cookie
	$cookie_file = __DIR__.'/cookie.txt';
	curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookie_file);
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);

	// UA
	$ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) '
		. 'AppleWebKit/537.36 (KHTML, like Gecko) '
		. 'Chrome/62.0.3202.62 Safari/537.36';
	curl_setopt($ch, CURLOPT_USERAGENT, $ua); 

	//执行并获取HTML文档内容
	$output = curl_exec($ch);

	$info = curl_getinfo($ch);

	curl_close($ch);
	return $output;
}


/**
 * 输入要查询的数据
 */
function input_data()
{
	// 读入文件
	$file = dirname(__DIR__).'/conf/input.txt';
	if (!file_exists($file)) {
		exit('输入文件不存在!!!');
	}
	$text = file_get_contents($file);
	$data = explode(PHP_EOL, $text);

	// 处理成域名
	foreach ($data as &$item) {
		$item = explode(',', trim($item, ','));
	}

	return $data;
}


/**
 * 输出CVS文件格式
 */
function output_data($data)
{
	$file = dirname(__DIR__).'/conf/output.csv';

	if (!file_exists($file)) {
		$title = '网站名称,域名,ICP号,'
			.'备案／许可证号,主办单位性质,主办单位名称,审核通过时间,'
			.'网站名称,网站首页网址,网站负责人姓名,网站备案／许可证号,网站域名,网站前置审批项,';
		file_put_contents($file, $title);
	}
	$str = join(',', $data);
	file_put_contents($file, PHP_EOL.$str, FILE_APPEND);
}


/**
 * 转换秒为 时:分:秒
 */
function sec2time($sec)
{
    $result = '00:00:00';  
    if ($sec>0) {  
        $hour   = floor($sec/3600);  
        $minute = floor(($sec-3600 * $hour)/60);  
        $second = floor((($sec-3600 * $hour) - 60 * $minute) % 60);  
        $result = sprintf('%02d:%02d:%02d', $hour, $minute, $second);
    }  
    return $result;  
}